﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using MobileBroadbandUserBlog.MBLM.Core;
using MobileBroadbandUserBlog.MBLM.Core.Interfaces;
using MobileBroadbandUserBlog.MBLM.Core;

namespace MobileBroadbandUserBlog.MBLM.Core
{
    public class MobileSoftwareLogger : IMobileSoftwareLogger
    {
        private IChangeStatistics _changeStatistics;
        private IDirectoryWatcher _directoryWatcher;

        private IMobileSoftware _mobileSoftware;

        public MobileSoftwareLogger(IMobileSoftware mobileSoftware) : this(mobileSoftware, new ChangeStatistics(new DateTimeContainer()), new DirectoryWatcher())
        {
        }

        public MobileSoftwareLogger(IMobileSoftware mobileSoftware, IChangeStatistics changeStatistics, IDirectoryWatcher directoryWatcher)
        {
            if (mobileSoftware == null)
            {
                throw new ArgumentNullException("mobileSoftware cannot be null.");
            }
            if (changeStatistics == null)
            {
                throw new ArgumentNullException("changeStatistics cannot be null.");
            }
            if (directoryWatcher == null)
            {
                throw new ArgumentNullException("mobileSoftware cannot be null.");
            }
            _changeStatistics = changeStatistics;
            _directoryWatcher = directoryWatcher;
            _mobileSoftware = mobileSoftware;
        }


        #region IMobileSoftwareLogger Members

        public override event FileChangeDelegate LoggingDetected;

        public override IMobileSoftware GetMobileSoftware()
        {
            return _mobileSoftware;
        }

        public override void StartLogging()
        {
            _changeStatistics.ResetStatistics();
            _directoryWatcher.StartWatcher(_mobileSoftware.GetFolderToMonitor(), _mobileSoftware.GetFileFilterToMonitor(), _watcher_Changed);
        }

        public override void StopLogging()
        {
            _directoryWatcher.StopWatcher();
        }

        void _watcher_Changed(string file, WatcherChangeTypes changeType)
        {
            _changeStatistics.AddToStatistics(DateTime.Now);
            OnLoggingDetected(file, changeType);
        }

        private void OnLoggingDetected(string file, WatcherChangeTypes changeType)
        {
            if (this.LoggingDetected != null)
            {
                this.LoggingDetected(file, changeType);
            }
        }

        public override IChangeStatistics GetChangeStatistics()
        {
            return _changeStatistics;
        }

        #endregion
    }
}
